package com.atguigu.srb.core.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.pojo.entity.excel.DictData;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

//@Component
public class DictExcelDataListener extends AnalysisEventListener<DictData> {
    //@Autowired 只能在组件类中 从管理组件类对象的容器中装配其他的对象
//    @Autowired
    DictMapper dictMapper;

    public DictExcelDataListener(DictMapper baseMapper) {
        this.dictMapper = baseMapper;
    }

    //因为导入的数据字典数据量较小  读取一行保存一行
    @Override
    public void invoke(DictData dictData, AnalysisContext analysisContext) {
        //1、id不能重复
        Integer count = dictMapper.selectCount(new LambdaQueryWrapper<Dict>()
                .eq(Dict::getId, dictData.getId()));
        if(count==0){
            //2、保存到数据库
            Dict dict = new Dict();
//            BeanUtils.copyProperties(dictData , dict); 如果dictData的属性名+类型和dict一样 可以将属性值拷贝给dict
            dict.setId(Long.parseLong(dictData.getId()));
            dict.setDictCode(dictData.getCode());
            dict.setName(dictData.getName());
            if(dictData.getValue()!=null){
                dict.setValue(Integer.parseInt(dictData.getValue()));
            }
            dict.setParentId(Long.parseLong(dictData.getParentId()));
            dictMapper.insert(dict);

        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
